﻿namespace SLClient.ViewModels
{
    using SLClient.Extension;
    using SLClient.Infrastructure;
    using SLClient.ServiceAPI;
    using SLClient.Views;
    using System;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Windows;
    using System.Windows.Input;
    using System.ComponentModel;

    public class UserBankViewModel : ViewModelBase
    {
        private string _accountPwd;
        private Visibility _accoutPwdVisibity;
        private Visibility _bankInfoVisibility;
        private string _bankName;
        private bool _canEdit;
        private string _confirmAccountPwd;
        private string _confirmPwd;
        private Visibility _confirmVisibity;
        private string _errMsg;
        private bool _isNew = false;
        private Visibility _loadingVisibity;
        private string _loginPwd;
        private UserBank _loginUserBank;
        private string _newPassword;
        private Visibility _psdVisibility;
        private Visibility _showDetailVisibity;
        private readonly UserBankView _userBankView;

        public UserBankViewModel(UserBankView userBankView)
        {
            this.ConfirmVisibity = Visibility.Visible;
            this._loadingVisibity = Visibility.Collapsed;
            this._showDetailVisibity = Visibility.Collapsed;
            this._accoutPwdVisibity = Visibility.Collapsed;
            this._loginUserBank = new UserBank();
            this._userBankView = userBankView;
            this.BankInfos = new ObservableCollection<BankInfo>();
            this._psdVisibility = Visibility.Visible;
            this._bankInfoVisibility = Visibility.Collapsed;
            this.CommandInit();
            this.LoadInfo();
        }

        public static void Cache(UserBank userBank)
        {
            new IsolatedStorageHelper<UserBank>().CreateSettingsInStorage("CurrentUserBank", userBank);
        }

        private void CommandInit()
        {
            this.TransitionCommand = new DelegateCommand(new Action<object>(this.Transition));
            RelayCommand command = new RelayCommand(this.Commit) {
                IsEnabled = true
            };
            this.CommitCommand = command;
        }

        public void Commit()
        {
            EventHandler<ChangePasswordCompletedEventArgs> handler = null;
            EventHandler<AsyncCompletedEventArgs> handler2 = null;
            EventHandler<AsyncCompletedEventArgs> handler3 = null;
            ServiceClient serviceClient = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
            if (this.PsdVisibility == 0)
            {
                if (string.IsNullOrEmpty(this.LoginPwd) || string.IsNullOrEmpty(this.NewPassword))
                {
                    this.ErrMsg = "密码不能为空!";
                    return;
                }
                if (this.NewPassword != this.ConfirmPwd)
                {
                    this.ErrMsg = "两次输入不一致!";
                    return;
                }
                if (this.NewPassword.Length < 6)
                {
                    this.ErrMsg = "密码太短（6位以上）";
                    return;
                }
                this.LoadingVisibity = 0;
                if (handler == null)
                {
                    handler = delegate (object obj, ChangePasswordCompletedEventArgs arg) {
                        if (!arg.Result)
                        {
                            this.ErrMsg = "原密码错误！";
                            this.LoadingVisibity = Visibility.Collapsed;
                        }
                        else
                        {
                            this._userBankView.DialogResult = true;
                        }
                    };
                }
                serviceClient.ChangePasswordCompleted += handler;
                serviceClient.ChangePasswordAsync(ViewDispatcher.LoginUser.UserAccount, this.LoginPwd, this.NewPassword);
            }
            else if (this.BankInfoVisibility == 0)
            {
                if (this.LoginUserBank.BankId == 0)
                {
                    this.ErrMsg = "请选择银行!";
                    return;
                }
                if (string.IsNullOrEmpty(this.LoginUserBank.BankNumber))
                {
                    this.ErrMsg = "银行户名不得为空!";
                    return;
                }
                if (string.IsNullOrEmpty(this.LoginUserBank.AccountName))
                {
                    this.ErrMsg = "银行户名不得为空!";
                    return;
                }
                if (string.IsNullOrEmpty(this.LoginUserBank.AccountPwd) || string.IsNullOrWhiteSpace(this.LoginUserBank.AccountPwd))
                {
                    this.ErrMsg = "密码不能为空!";
                    return;
                }
                if (this.LoginUserBank.AccountPwd.Length < 6)
                {
                    this.ErrMsg = "密码太短（6位以上）";
                    return;
                }
                if (this.LoginUserBank.AccountPwd != this.ConfirmAccountPwd)
                {
                    this.ErrMsg = "两次输入不一致!";
                    return;
                }
                this.LoadingVisibity = 0;
                serviceClient.GetBankInfoByUserIdCompleted += delegate (object obj, GetBankInfoByUserIdCompletedEventArgs arg) {
                    arg.Result.AccountPwd = DesHelper.DesDecrypt(arg.Result.AccountPwd);
                    Cache(arg.Result);
                };
                if (handler2 == null)
                {
                    handler2 = delegate (object obj, AsyncCompletedEventArgs arg) {
                        if (arg.Error != null)
                        {
                            this.ErrMsg = "填写资料发生错误！";
                            this.LoadingVisibity = Visibility.Collapsed;
                        }
                        else
                        {
                            serviceClient.GetBankInfoByUserIdAsync(ViewDispatcher.LoginUser.UserId);
                            this._userBankView.DialogResult = true;
                        }
                    };
                }
                serviceClient.UpdateUserBankInfoCompleted += handler2;
                serviceClient.UpdateUserBankInfoAsync(this.LoginUserBank);
            }
            if (this.AccoutPwdVisibity == 0)
            {
                if (string.IsNullOrEmpty(this.AccountPwd) || string.IsNullOrEmpty(this.NewPassword))
                {
                    this.ErrMsg = "密码不能为空!";
                }
                else if (this.NewPassword.Length < 6)
                {
                    this.ErrMsg = "密码太短（6位以上）";
                }
                else if (this.NewPassword != this.ConfirmPwd)
                {
                    this.ErrMsg = "两次输入不一致!";
                }
                else if (this.AccountPwd != ViewDispatcher.CurrentUserBank.AccountPwd)
                {
                    this.ErrMsg = "原密码错误!";
                }
                else
                {
                    this.LoadingVisibity = 0;
                    this.LoginUserBank.AccountPwd = this.NewPassword;
                    serviceClient.GetBankInfoByUserIdCompleted += delegate (object obj, GetBankInfoByUserIdCompletedEventArgs arg) {
                        arg.Result.AccountPwd = DesHelper.DesDecrypt(arg.Result.AccountPwd);
                        Cache(arg.Result);
                    };
                    if (handler3 == null)
                    {
                        handler3 = delegate (object obj, AsyncCompletedEventArgs arg) {
                            if (arg.Error != null)
                            {
                                this.ErrMsg = "更新密码发生错误！";
                                this.LoadingVisibity = Visibility.Collapsed;
                            }
                            else
                            {
                                serviceClient.GetBankInfoByUserIdAsync(ViewDispatcher.LoginUser.UserId);
                                this._userBankView.DialogResult = true;
                            }
                        };
                    }
                    serviceClient.UpdateUserBankInfoCompleted += handler3;
                    serviceClient.UpdateUserBankInfoAsync(this.LoginUserBank);
                }
            }
        }

        private void LoadInfo()
        {
            Func<BankInfo, bool> func1 = null;
            ServiceClient instance = WCFServicesUtil<ServiceClient>.GetInstance(ServiceType.ServiceAPI);
            instance.GetAllBankInfoCompleted += delegate (object obj, GetAllBankInfoCompletedEventArgs arg) {
                if (arg.Error == null)
                {
                    new IsolatedStorageHelper<ObservableCollection<BankInfo>>().CreateSettingsInStorage("Banks", arg.Result);
                    foreach (BankInfo info in arg.Result)
                    {
                        this.BankInfos.Add(info);
                    }
                }
            };
            instance.GetBankInfoByUserIdCompleted += delegate (object obj, GetBankInfoByUserIdCompletedEventArgs arg)
            {
                Func<BankInfo, bool> func2 = null;
                if (arg.Result != null)
                {
                    this.LoginUserBank = arg.Result;
                    this.LoginUserBank.AccountPwd = DesHelper.DesDecrypt(arg.Result.AccountPwd);
                    this.CanEdit = true;
                    if (func2 == null)
                    {
                        func2= new Func<BankInfo, bool>((s)=>{return ((s.Id == this.LoginUserBank.BankId));});
                    }
                    BankInfo info = Enumerable.FirstOrDefault<BankInfo>(this.BankInfos, func2);
                    if (info != null)
                    {
                        this.BankName = info.Name;
                    }
                    this.BankInfoVisibility = Visibility.Collapsed;
                }
                else
                {
                    this.LoginUserBank = new UserBank();
                    this.LoginUserBank.UserId = ViewDispatcher.LoginUser.UserId;
                    this.CanEdit = false;
                }
                Cache(this.LoginUserBank);
            };
            if (!IsolatedStorageHelper<ObservableCollection<BankInfo>>.IsSettingPersisted("Banks"))
            {
                instance.GetAllBankInfoAsync();
            }
            else
            {
                this.BankInfos = ViewDispatcher.Banks;
            }
            if (!IsolatedStorageHelper<ObservableCollection<UserBank>>.IsSettingPersisted("CurrentUserBank"))
            {
                instance.GetBankInfoByUserIdAsync(ViewDispatcher.LoginUser.UserId);
            }
            else
            {
                this.LoginUserBank = ViewDispatcher.CurrentUserBank;
                if (string.IsNullOrEmpty(ViewDispatcher.CurrentUserBank.AccountName) || string.IsNullOrEmpty(ViewDispatcher.CurrentUserBank.BankNumber))
                {
                    this.CanEdit = false;
                }
                else
                {
                    this.CanEdit = true;
                    if (func1 == null)
                    {
                        func1 = new Func<BankInfo, bool>((s) => { return ((s.Id == this.LoginUserBank.BankId)); });
                    }
                    BankInfo info = Enumerable.FirstOrDefault<BankInfo>(this.BankInfos, func1);
                    if (info != null)
                    {
                        this.BankName = info.Name;
                    }
                    this.BankInfoVisibility = Visibility.Collapsed;
                }
            }
        }

        public void Transition(object sender)
        {
            if (!this.CanEdit)
            {
                if (this._psdVisibility == Visibility.Collapsed)
                {
                    this.PsdVisibility = Visibility.Visible;
                    this.BankInfoVisibility = Visibility.Collapsed;
                    this.LoginPwd = "";
                    this.NewPassword = "";
                    this.ConfirmPwd = "";
                }
                else
                {
                    this.LoginUserBank.AccountName = "";
                    this.LoginUserBank.BankNumber = "";
                    this.LoginUserBank.BankId = 0;
                    this.LoginUserBank.AccountPwd = "";
                    this.PsdVisibility = Visibility.Collapsed;
                    this.BankInfoVisibility = Visibility.Visible;
                    this.ShowDetailVisibity = Visibility.Collapsed;
                }
            }
            else
            {
                string str2 = sender.ToString();
                if (str2 != null)
                {
                    if (!(str2 == "changeLoginPwd"))
                    {
                        if (str2 == "changeBankPwd")
                        {
                            this.PsdVisibility = Visibility.Collapsed;
                            this.AccoutPwdVisibity = Visibility.Visible;
                            this.ShowDetailVisibity = Visibility.Collapsed;
                            this.ConfirmVisibity = Visibility.Visible;
                        }
                        else if (str2 == "showBankInfo")
                        {
                            this.PsdVisibility = Visibility.Collapsed;
                            this.AccoutPwdVisibity = Visibility.Collapsed;
                            this.ShowDetailVisibity = Visibility.Visible;
                            this.ConfirmVisibity = Visibility.Collapsed;
                        }
                    }
                    else
                    {
                        this.PsdVisibility = Visibility.Visible;
                        this.AccoutPwdVisibity = Visibility.Collapsed;
                        this.ShowDetailVisibity = Visibility.Collapsed;
                        this.ConfirmVisibity = Visibility.Visible;
                    }
                }
            }
            this.ErrMsg = "";
        }

        public string AccountPwd
        {
            get
            {
                return this._accountPwd;
            }
            set
            {
                this._accountPwd = value;
                base.Notify<string>(() => this.AccountPwd);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_AccountPwd)), new ParameterExpression[0]));
            }
        }

        public Visibility AccoutPwdVisibity
        {
            get
            {
                return this._accoutPwdVisibity;
            }
            set
            {
                this._accoutPwdVisibity = value;
                base.Notify<Visibility>(() => this.AccoutPwdVisibity);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_AccoutPwdVisibity)), new ParameterExpression[0]));
            }
        }

        public ObservableCollection<BankInfo> BankInfos { get; set; }

        public Visibility BankInfoVisibility
        {
            get
            {
                return this._bankInfoVisibility;
            }
            set
            {
                this._bankInfoVisibility = value;
                base.Notify<Visibility>(() => this.BankInfoVisibility);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_BankInfoVisibility)), new ParameterExpression[0]));
            }
        }

        public string BankName
        {
            get
            {
                return this._bankName;
            }
            set
            {
                this._bankName = value;
                base.Notify<string>(() => this.BankName);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_BankName)), new ParameterExpression[0]));
            }
        }

        public bool CanEdit
        {
            get
            {
                return this._canEdit;
            }
            set
            {
                this._canEdit = value;
                base.Notify<bool>(() => this.CanEdit);
                //base.Notify<bool>(System.Linq.Expressions.Expression.Lambda<Func<bool>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_CanEdit)), new ParameterExpression[0]));
            }
        }

        public ICommand CommitCommand { get; set; }

        public string ConfirmAccountPwd
        {
            get
            {
                return this._confirmAccountPwd;
            }
            set
            {
                this._confirmAccountPwd = value;
                base.Notify<string>(() => this.ConfirmAccountPwd);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_ConfirmAccountPwd)), new ParameterExpression[0]));
            }
        }

        public string ConfirmPwd
        {
            get
            {
                return this._confirmPwd;
            }
            set
            {
                this._confirmPwd = value;
                base.Notify<string>(() => this.ConfirmPwd);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_ConfirmPwd)), new ParameterExpression[0]));
            }
        }

        public Visibility ConfirmVisibity
        {
            get
            {
                return this._confirmVisibity;
            }
            set
            {
                this._confirmVisibity = value;
                base.Notify<Visibility>(() => this.ConfirmVisibity);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_ConfirmVisibity)), new ParameterExpression[0]));
            }
        }

        public string ErrMsg
        {
            get
            {
                return this._errMsg;
            }
            set
            {
                this._errMsg = value;
                base.Notify<string>(() => this.ErrMsg);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_ErrMsg)), new ParameterExpression[0]));
            }
        }

        public Visibility LoadingVisibity
        {
            get
            {
                return this._loadingVisibity;
            }
            set
            {
                this._loadingVisibity = value;
                base.Notify<Visibility>(() => this.LoadingVisibity);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_LoadingVisibity)), new ParameterExpression[0]));
            }
        }

        public string LoginPwd
        {
            get
            {
                return this._loginPwd;
            }
            set
            {
                this._loginPwd = value;
                base.Notify<string>(() => this.LoginPwd);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_LoginPwd)), new ParameterExpression[0]));
            }
        }

        public UserBank LoginUserBank
        {
            get
            {
                return this._loginUserBank;
            }
            set
            {
                this._loginUserBank = value;
                base.Notify<UserBank>(() => this.LoginUserBank);
                //base.Notify<UserBank>(System.Linq.Expressions.Expression.Lambda<Func<UserBank>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_LoginUserBank)), new ParameterExpression[0]));
            }
        }

        public string NewPassword
        {
            get
            {
                return this._newPassword;
            }
            set
            {
                this._newPassword = value;
                base.Notify<string>(() => this.NewPassword);
                //base.Notify<string>(System.Linq.Expressions.Expression.Lambda<Func<string>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_NewPassword)), new ParameterExpression[0]));
            }
        }

        public Visibility PsdVisibility
        {
            get
            {
                return this._psdVisibility;
            }
            set
            {
                this._psdVisibility = value;
                base.Notify<Visibility>(() => this.PsdVisibility);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_PsdVisibility)), new ParameterExpression[0]));
            }
        }

        public Visibility ShowDetailVisibity
        {
            get
            {
                return this._showDetailVisibity;
            }
            set
            {
                this._showDetailVisibity = value;
                base.Notify<Visibility>(() => this.ShowDetailVisibity);
                //base.Notify<Visibility>(System.Linq.Expressions.Expression.Lambda<Func<Visibility>>(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(UserBankViewModel)), (MethodInfo)(UserBankViewModel.get_ShowDetailVisibity)), new ParameterExpression[0]));
            }
        }

        public ICommand TransitionCommand { get; set; }
    }
}

